import Schema from 'async-validator'

// 定义请求根路径baseUrl
   const baseUrl="https://www.ailustny.cn/prod-api"
  // const baseUrl = "http://localhost:8080";
// 同时并发请求的次数
let ajaxTimes = 0;
const app = getApp().globalData //获取并设置tabbar

/**
 * 返回基本路径
 */
export const getBaseUrl = () => {
  return baseUrl;
}

/**
 * 用户登录
 */
export const getWxlogin = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      timeout: 5000,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

/**
 * 获取用户信息
 */
export const getUserProfile = () => {
  return new Promise((resolve, reject) => {
    wx.getUserProfile({
      desc: '获取用户信息',
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}
/**
 * 微信支付
 * @param  pay
 */
export const requestPay = (pay) => {
  return new Promise((resolve, reject) => {
    wx.requestPayment({
      ...pay,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })

  })
}
/**
 * 请求后端接口封装
 * @param {} params
 */
export const requestUrl = (params) => {
  let header = { ...params.header }
  header["token"] = wx.getStorageSync('token')
  var statrt = new Date();
  ajaxTimes++;
  //弹出加载框，mask：是否可以点击 mask true:否;false:是
  wx.showLoading({
    title: '加载中...',
    mask: true
  })
  // 模拟网络延迟加载...
  while (true) {
    if (new Date().getTime() - start > 1 * 100) break;
  }
  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      header,
      url: baseUrl + params.url,
      success: (res) => {
        resolve(red)
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        ajaxTimes--;
        if (ajaxTimes == 0) {
          wx.hideLoading();  // 关闭加载图标
        }
      }
    })
  })
}
/**
 * 访问后端接口
 * @param {*} url 访问地址
 * @param {*} data  参数
 * @param {*} method  请求方式
 */
export const request = ({ url, method, data }) => {
  let token = wx.getStorageSync('token')
  if (!token) {
    wx.reLaunch({
      url: '/pages/pre_index/index'
    });
    return
  }
  const head = {
    'content-type': 'application/json',
    "Authorization": "Bearer " + token
  }
  wx.showLoading({
    title: '加载中...',
    mask: true
  })
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      data: data,
      header: head,
      method: method,
      success: (res) => {
        wx.hideLoading();
        console.log('res', res)
        if (res.data.code === 401) {
          wx.showToast({
            title: '登录失效，请重新登录',
            icon: 'none',
            duration: 1500,
            success: function () {
              setTimeout(function () {
                wx.clearStorage();
                wx.reLaunch({
                  url: '/pages/pre_index/index'
                });
              }, 1500)
            }
          })
          return
        } else if (res.data.code === 500) {
          wx.showToast({
            title: res.data.msg ? res.data.msg : '',
            icon: 'none',
            duration: 5000
          });

        } else if (res.data.code === 200 && res.data.msg && (method != 'get' && method != 'GET')) {
          wx.showToast({
            title: res.data.msg ? res.data.msg : '',
            icon: 'none',
            duration: 2000
          });

        }
        resolve(res);
      },
      fail: (err) => {
        wx.hideLoading();
        reject(err)
      },
      complete: () => {

      }
    })
  })
}
/**
 * 获取微信授权码
 */
export const getWxaCode = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        return resolve(res.code)
      },
      fail() {
        wx.showToast({
          title: '获取code失败',
          icon: 'none'
        })
        return resolve('获取code失败')
      }
    })
  })
}

export const logIn = ({ url, data }) => {
  if (!data.code) data.code = "alApp"
  const head = {
    'content-type': 'application/json'
  }
  wx.showLoading({
    title: '登录中...',
    mask: true
  })
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      data: data,
      header: head,
      method: 'POST',
      success: (res) => {
        wx.hideLoading();
        if (res.data.code === 200) {
          console.log('登录成功')
          console.log('res.data.token', res.data.data.token)
          setRouter(res.data.data.menus);
          wx.setStorageSync('token', res.data.data.token);
          wx.setStorageSync('menus', res.data.data.menus)
          resolve(res);
        } else if (res.data.code === 500) {
          wx.showToast({
            title: res.data.msg ? res.data.msg : '',
            icon: 'none',
            duration: 5000
          });
        }
        resolve(res);
      },
      fail: (err) => {
        console.log(err)
        wx.hideLoading();
        reject(err)
      },
      complete: () => {

      }
    })
  })
}

export const upload = (file, watermark) => {
  wx.showLoading({
    title: '上传中...',
    mask: true
  })
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: getBaseUrl() + '/bus/file/upload?watermark=' + watermark,
      filePath: file.url,
      name: 'file',
      header: {
        "Content-Type": "multipart/form-data",
        "Authorization": "Bearer " + wx.getStorageSync('token')
      },
      success(res) {
        const data = JSON.parse(res.data)
        if (data.code == 200) {
          resolve(res.data)
        } else {
          wx.showToast({
            title: res.data.msg ? res.data.msg : '',
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (err) {
        reject(err)
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  })
}
//设置
export function setRouter(menus) {
  if (!menus || menus.length == 0) return
  let routerList = menus.map(v => {
    return {
      name: v.menuName,
      icon: v.icon,
      url: v.path,
      component: v.component
    }
  })
  wx.setStorageSync('routerList', JSON.stringify(routerList));
}
/**
 * 获取当前位置
 */
export const getLocation = () => {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

/**
 *
 * @param {拨打电话} phoneNumber
 */
export const makePhoneCallHandler = (phoneNumber) => {
  console.log('phoneNumber', phoneNumber)
  return new Promise((resolve, reject) => {
    wx.makePhoneCall({
      phoneNumber: phoneNumber,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}
//导航
export const navigationHandler = (latitude, longitude, name) => {
  name = name || ''
  return new Promise((resolve, reject) => {
    wx.openLocation({
      name: name,
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude),
      scale: 18,
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err)
      }
    });
  })
}
//获取当前位置（可筛选）
export const chooseLocation = () => {
  return new Promise((resolve, reject) => {
    wx.chooseLocation({
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err)
      }
    });
  })
}
/**
 *
 * @param {将对象转为路径参数} params
 */
export const paramsHander = (params) => {
  // 将参数转换为查询字符串
  return Object.keys(params)
    .map(key => `${key}=${params[key]}`)
    .join('&');
}
// 数据校验
export const validator = (params,rules)=>{
  const validator = new Schema(rules)
  return new Promise((resolve) => {
    validator.validate(params, (errors) => {
      if (errors) {
        wx.showToast({ icon: 'none',title: errors[0].message })
        resolve({ valid: false })
      } else {
        resolve({ valid: true })
      }
    })
  })
}



